﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class ResManager : SingletonManager<ResManager>
{
    public bool IS_AB_MODE = true;

    const string manifestName = "AssetBundleManifest";
    Dictionary<string, ResVersionItem> bundleDic = new Dictionary<string, ResVersionItem>();
    AssetBundleManifest manifest;

    public void Start ()
    {
        bundleDic = BundleUpdateManager.Instance.resVersion.bundleDic;
        AssetBundle mainAb = AssetBundle.LoadFromFile(PathDefine.PERSISTENT_DATA + PathDefine.ANDROID);
        manifest = mainAb.LoadAsset<AssetBundleManifest>(manifestName);
        foreach (var name in manifest.GetAllAssetBundles())
        {
            Hash128 hash = manifest.GetAssetBundleHash(name);
            Debug.Log(hash.ToString());
        }
        mainAb.Unload(false);
    }

    public byte[] LoadLuaBytes(string path)
    {
        if (IS_AB_MODE)
        {
            path = PathDefine.RESOURCES_ASSET + "Lua/" + path.ToLower() + ".bytes";
            if (!bundleDic.ContainsKey(path))
            {
                Debug.LogError("没有找到对应的文件:" + path);
                return null;
            }
            string guid = bundleDic[path].guid;
            string bundlePath = PathDefine.PERSISTENT_DATA + guid;
            AssetBundle ab = AssetBundle.LoadFromFile(bundlePath);
            TextAsset t = ab.LoadAsset<TextAsset>(Path.GetFileNameWithoutExtension(path));
            byte[] bytes = t.bytes;
            ab.Unload(false);
            return bytes;
        }
        else
        {
            string luaRootPath = PathDefine.LUA_CODE_ROOT;
            path = luaRootPath + path + ".lua";
            if (!File.Exists(path))
            {
                Debug.LogError(path + "不存在");
                return null;
            }
            return File.ReadAllBytes(path);
        }

    }
}
